/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.sys.customerstatus.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import cn.knet.sp.ncrm.common.beanvalidator.BeanValidators;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.modules.sys.customerstatus.entity.CustomerStatus;
import cn.knet.sp.ncrm.modules.sys.customerstatus.service.CustomerStatusService;
import cn.knet.sp.ncrm.modules.sys.customerstatusdetail.entity.CustomerStatusDetail;
import cn.knet.sp.ncrm.modules.sys.customerstatusdetail.service.CustomerStatusDetailService;
import cn.knet.sp.ncrm.modules.sys.utils.CustomerUtils;

/**
 * 客户状态
 * @author zhangbin
 * @version 2015 -08-28
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/customerStatus")
public class CustomerStatusController extends BaseController {

	@Autowired
	private CustomerStatusService customerStatusService;

	@Autowired
	private CustomerStatusDetailService customerStatusDetailService;
	
	@ModelAttribute
	public CustomerStatus get(@RequestParam(required=false) String id) {
		CustomerStatus entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = customerStatusService.get(id);
		}
		if (entity == null){
			entity = new CustomerStatus();
		}
		return entity;
	}

	/**
	 * 去空格
	 * @author zhangbin
	 * @date 2015 /08/28 16:59:59
	 * void
	 * @param customerStatus the customer status
	 */
	private void trim(CustomerStatus customerStatus) {
		if(customerStatus!=null&&StringUtils.isNotBlank(customerStatus.getContent())){
			customerStatus.setContent(StringUtils.trim(customerStatus.getContent()));
		}
	}

	/**
	 * 进入index
	 * @author zhangbin
	 * @date 2015 /08/28 16:59:50
	 * string
	 * @param customerStatus the customer status
	 * @param request the request
	 * @param response the response
	 * @param model the model
	 * @return the string
	 */
	@RequiresPermissions("sys:customerStatus:view")
	@RequestMapping(value = {"list", ""})
	public String list(CustomerStatus customerStatus, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/sys/customerstatus/customerStatusAjaxList";
	}

	/**
	 * ajax查询
	 * @author zhangbin
	 * @date 2015 /08/28 16:59:42
	 * @param customerStatus the customer status
	 * @param request the request
	 * @param response the response
	 * @param model the model
	 * @return the page
	 */
	@RequiresPermissions("sys:customerStatus:view")
	@RequestMapping(value = "listAjaxData")
	@ResponseBody
	public Page listAjaxData(CustomerStatus customerStatus, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CustomerStatus> page = customerStatusService.findPage(new Page<CustomerStatus>(request, response),
																   customerStatus);
		return page;
	}


	/**
	 * 查询,显示
	 * @author zhangbin
	 * @date 2015 /08/28 17:00:09
	 * string
	 * @param customerStatus the customer status
	 * @param model the model
	 * @return the string
	 */
	@RequiresPermissions("sys:customerStatus:view")
	@RequestMapping(value = "form")
	public String form(CustomerStatus customerStatus, Model model) {
	    customerStatus.addHistoryFlag();
		Map<String, String> operationList = new HashMap<String, String>();
		operationList.put("CREATE","创建");
		operationList.put("DONE","成单");
		operationList.put("END","结束");
		if(StringUtils.isNotBlank(customerStatus.getOperation())){
			customerStatus.setOperations(customerStatus.getOperation().split(","));
		}
		if(!customerStatus.getIsNewRecord()){
			CustomerStatusDetail detail = new CustomerStatusDetail();
			detail.setCustomerStatusId(customerStatus.getId());
			List<CustomerStatusDetail> list = customerStatusDetailService.findList(detail);
			model.addAttribute("customerStatusDetails", list);
		}
		model.addAttribute("customerStatus", customerStatus);
		model.addAttribute("operationList",operationList);
		return "modules/sys/customerstatus/customerStatusForm";
	}

	/**
	 * 更新和添加
	 * @author zhangbin
	 * @date 2015 /08/28 17:00:19
	 * string
	 * @param customerStatus the customer status
	 * @param model the model
	 * @param redirectAttributes the redirect attributes
	 * @return the string
	 */
	@RequiresPermissions("sys:customerStatus:edit")
	@RequestMapping(value = "save")
	public String save(CustomerStatus customerStatus, Model model, RedirectAttributes redirectAttributes) {
		this.trim(customerStatus);
		if (!beanValidator(model, customerStatus)){
			return form(customerStatus, model);
		}
		if(customerStatus.getIsNewRecord()){
			customerStatus.setDateCreated(new java.util.Date());
		}
		int count = customerStatusService.findDistinctCustomerStatus(customerStatus);
		if(count>0){
			addMessage(model, "客户状态状态["+customerStatus.getContent()+"]已经存在,请更换名称");
			return form(customerStatus, model);
		}
		if(customerStatus.getOperations()!=null){
			customerStatus.setOperation(StringUtils.join(customerStatus.getOperations(),","));
		}
		customerStatus.setLastUpdated(new java.util.Date());//必加修改时间
		customerStatusService.save(customerStatus);
		CustomerUtils.clearStatus(customerStatus);
		//清空缓存
		addMessage(redirectAttributes, "保存客户状态成功");
		return "redirect:"+Global.getAdminPath()+"/sys/customerStatus/?repage";
	}

	/**
	 * 删除
	 * @author zhangbin
	 * @date 2015 /08/28 17:00:26
	 * object
	 * @param customerStatus the customer status
	 * @param redirectAttributes the redirect attributes
	 * @return the object
	 */
	@RequiresPermissions("sys:customerStatus:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public Object delete(CustomerStatus customerStatus, RedirectAttributes redirectAttributes) {
		AjaxMessage result = AjaxMessage.success();
		try {
			customerStatusService.delete(customerStatus);
			CustomerUtils.clearStatus(customerStatus); //注意 这里不再对子做级联删除
			result.setMessage("删除客户状态成功!");
		} catch (Exception e) {
			logger.warn("删除客户状态失败", e);
			result.makeError("删除客户状态失败!系统发生异常");
		}
		return result;
	}

	/***************************
	 * 明细部分
	 ***************************/

	/**
	 * 查询明细
	 * @author zhangbin
	 * @date 2015 /08/28 16:59:36
	 * string
	 * @param customerStatusDetail the customer status detail
	 * @param request the request
	 * @param response the response
	 * @param model the model
	 * @return the string
	 */
	@RequiresPermissions("sys:customerStatus:view")
	@RequestMapping(value = "detail")
	@ResponseBody
	public Object detail(CustomerStatusDetail customerStatusDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxMessage result = AjaxMessage.success();
		List<CustomerStatusDetail> list = null;
		try {
			list = customerStatusDetailService.findList(customerStatusDetail);
			if(list.size()>0){
				result.put("list",list);
			}else{
				result.makeError("无记录");
			}
		} catch (Exception e) {
			logger.warn("查询用户状态明细发生异常",e);
			result.makeError("查询用户状态明细发生异常");
		}
		return result;
	}

	@RequiresPermissions("sys:customerStatus:view")
	@RequestMapping(value = "listDetailAjaxData")
	@ResponseBody
	public Page listAjaxData(CustomerStatusDetail customerStatusDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CustomerStatusDetail> page = customerStatusDetailService.findPage(new Page<CustomerStatusDetail>(request, response), customerStatusDetail);
		return page;
	}

	@RequiresPermissions("sys:customerStatus:edit")
	@RequestMapping(value = "detailSave")
	@ResponseBody
	public Object detailSave(CustomerStatusDetail customerStatusDetail, Model model, RedirectAttributes redirectAttributes) {
		AjaxMessage result = AjaxMessage.success();
		if(customerStatusDetail!=null&&StringUtils.isNotBlank(customerStatusDetail.getCauseDesc())){
			customerStatusDetail.setCauseDesc(StringUtils.trim(customerStatusDetail.getCauseDesc()));
		}
		try{
			BeanValidators.validateWithException(validator, customerStatusDetail);
			if(customerStatusDetail.getIsNewRecord()){
				customerStatusDetail.setDateCreated(new java.util.Date());
			}

			int count = customerStatusDetailService.findDistinctCustomerStatus(customerStatusDetail);
			if(count>0){
				result.makeError("客户状态状态["+customerStatusDetail.getCauseDesc()+"]已经存在,请更换名称");
				return result;
			}
			customerStatusDetail.setLastUpdated(new java.util.Date());//必加修改时间
			customerStatusDetailService.save(customerStatusDetail);
			CustomerUtils.clearDetail(customerStatusDetail);
			result.setMessage("保存客户状态明细成功");
		} catch(ConstraintViolationException ex){
			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
			list.add(0, "数据验证失败：");
			result.makeError(list.toArray(new String[]{}).toString());
		} catch (Exception e){
			result.makeError("保存客户状态明细发生异常");
		}
		return result;
	}

	@RequiresPermissions("sys:customerStatus:edit")
	@RequestMapping(value = "detailDelete")
	@ResponseBody
	public Object detailDelete(CustomerStatusDetail customerStatusDetail, RedirectAttributes redirectAttributes) {
		AjaxMessage result = AjaxMessage.success();
		try {
			customerStatusDetailService.delete(customerStatusDetail);
			CustomerUtils.clearDetail(customerStatusDetail);
			result.appendMessage("删除客户状态明细成功!");
		} catch (Exception e) {
			logger.warn("删除客户状态明细失败", e);
			result.makeError("删除客户状态明细失败!系统发生异常");
		}
		return result;
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "selectStatus")
	@ResponseBody
	public Object selectStatus(String type){
		AjaxMessage result = AjaxMessage.success();
		List<CustomerStatus> list = CustomerUtils.listStatus();
		result.put("list",list);
		if("select".equals(type)){
			StringBuffer buffer = new StringBuffer();
			for(CustomerStatus status:list){
				buffer.append("<option ");
				buffer.append("value='"+status.getId()+"' ");
				buffer.append("data-operation='"+status.getOperation()+"' ");
				buffer.append(">"+status.getContent());
				buffer.append("</option>");
			}
			result.put("select",buffer.toString());
		}
		return result;
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "selectDetail")
	@ResponseBody
	public Object selectDetail(String id,String type){
		AjaxMessage result = AjaxMessage.success();
		List<CustomerStatusDetail> list = CustomerUtils.listStatusDetail(id);
		result.put("list",list);
		if("select".equals(type)){
			StringBuffer buffer = new StringBuffer();
			for(CustomerStatusDetail status:list){
				buffer.append("<option ");
				buffer.append("value='"+status.getId()+"' ");
				buffer.append(">"+status.getCauseDesc());
				buffer.append("</option>");
			}
			result.put("select",buffer.toString());
		}
		return result;
	}
}